package com.xiaoxu.intranetweb.util.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.extension.service.IService;


import java.util.List;

public class EasyExcelListener<T> implements ReadListener<T> {
    public static final int BATCH_COUNT = 10000;

    private IService<T> baseService;

    /**
     *临时存储
     */
    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public EasyExcelListener(IService<T> baseService){
        this.baseService = baseService;
    }

    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }


    private void saveData() {
        baseService.saveBatch(cachedDataList);
    }
}
